package com.epam.photographer;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.DispatcherServlet;

import com.epam.photographer.controllers.FillController;
import com.epam.photographer.controllers.ServiceController;
import com.epam.photographer.model.PhotoWrapper;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);
	@Autowired
	private FillController fillController;
	@Autowired
	private ServiceController serviceController;

	/**
	 * Simply selects the home view to render by returning its name.
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) throws IOException {
		logger.info("Welcome home! The client locale is {}.", locale);
		// fillController.fillDB();
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
				DateFormat.LONG, locale);
		//fillController.fillDB();
		String formattedDate = dateFormat.format(date);

		model.addAttribute("albums", serviceController.getAlbums());
		model.addAttribute("serverTime", formattedDate);

		return "home";
	}

	@RequestMapping(value = "/{name}", method = RequestMethod.GET)
	public String index2(HttpServletResponse response,
			@PathVariable("name") String pageName) throws IOException {

		return pageName;
	}

	@RequestMapping(value = "/getUserImage/{id}")
	public void getUserImage(HttpServletResponse response,
			@PathVariable("id") int tweetID) throws IOException {

		response.setContentType("image/jpeg");
		PhotoWrapper photo = serviceController.getPhoto(tweetID);
		String url = photo.getUrl();

		BufferedImage im = ImageIO.read(new File(url));

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(im, "jpg", baos);
		baos.flush();
		byte[] imageInByte = baos.toByteArray();

		// short[] buffer =
		// ((DataBufferShort)im.getRaster().getDataBuffer()).getData();//tweetService.getTweetByID(tweetID).getUserImage();
		InputStream in1 = new ByteArrayInputStream(imageInByte);
		IOUtils.copy(in1, response.getOutputStream());
	}

	@RequestMapping(value = "/manamana")
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			boolean isMultipart = FileUpload.isMultipartContent(request);

			if (isMultipart) {
				DiskFileUpload upload = new DiskFileUpload();
				List items = null;

				try {
					items = upload.parseRequest(request);
				} catch (FileUploadException ex) {
				}
				Iterator itr = items.iterator();

				while (itr.hasNext()) {
					FileItem item = (FileItem) itr.next();

					if (item.isFormField()) {

						String fieldName = item.getFieldName();

					} else {

						File fullFile = new File(item.getName());
						PhotoWrapper photo = new PhotoWrapper();
						photo.setTitle("12313");
						File savedFile = new File(request.getSession()
								.getServletContext().getRealPath("/")
								+ "/resources/imagesManamana",
								fullFile.getName());
						photo.setUrl(savedFile.getPath());
						serviceController.setaddPhotoWrapper(photo);
						try {
							item.write(savedFile);
						} catch (Exception ex) {
						}
					}
				}

			}
		} finally {
			// out.close();
		}
	}

}